package cur.tool.common.filter;

import cur.nature.framework.core.log.LOG;
import cur.nature.framework.core.thread.MyThreadLocal;
import cur.nature.framework.core.util.JsonUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

@RestControllerAdvice
public class CustomRequestBodyAdvice implements RequestBodyAdvice {


    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.hasParameterAnnotation(RequestBody.class);
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
            return  httpInputMessage;
        //        return new HttpInputMessage() {
//            @Override
//            public InputStream getBody() throws IOException {
//                LogUtil.info("此处进行解密数据");
//                return new ByteArrayInputStream(IOUtils.toString(httpInputMessage.getBody()).replace("-encrypt", "").getBytes(StandardCharsets.UTF_8));
//            }
//
//            @Override
//            public HttpHeaders getHeaders() {
//                return httpInputMessage.getHeaders();
//            }
//        };
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        String param = ((o!=null)? JsonUtil.toJSONString(o):null);
        MyThreadLocal.getCurrentThread().put(MyThreadLocal.PARAM, param);
        LOG.info("请求参数: "+param);
        return o;
    }
}
